﻿using SharpPcap;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Services.Equ.PcapCommunication.Operation
{
    /// <summary>
    /// 批量操作
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class BatchOperation<T>
    {
        public List<PcapOperation<T>> PcapOperations{ get; set; }
        public int FinalResultIndex { get; set; }
        public ILiveDevice Device { get; set; }
        public Func<T,bool> TrueCondition { get; set; }
        /// <summary>
        /// ctor
        /// </summary>
        /// <param name="finalResultIndex">最终结果的索引</param>
        /// <param name="trueCondition">如何判断返回结果为成功</param>
        /// <param name="pcapOperation">设备通讯类</param>
        public BatchOperation(int finalResultIndex, Func<T, bool> trueCondition, params PcapOperation<T>[] pcapOperation)
        {
            PcapOperations = [.. pcapOperation];
            FinalResultIndex = finalResultIndex;
            TrueCondition = trueCondition;
            Device = PcapOperations.First().Device;
            PcapOperations.ForEach(item =>
            {
                item.IsAutoControlDevice = false;
            });
        }
        /// <summary>
        /// 获取批量操作结果
        /// </summary>
        /// <returns>字典 key为mac地址 value为操作结果</returns>
        public async Task<Dictionary<string, bool>> GetOperationResult()
        {
            Dictionary<string, bool> result = [];
            Dictionary<string,Task<Dictionary<int,List<T>>?> > resultList = [];
            Device.Open();
            foreach(var item in PcapOperations)
            {
                var r= item.GetOperationResult();
                string mac=BitConverter.ToString(item.DestinationMac.GetAddressBytes());
                resultList.Add(mac, r);
            }
            await Task.WhenAll(resultList.Values);
            foreach(string key in resultList.Keys)
            {
                var r= resultList[key].GetAwaiter().GetResult();
                if(r!=null && r.TryGetValue(FinalResultIndex,out var subr))
                {
                    if(subr!=null && subr.Any(TrueCondition))
                    {
                        result.Add(key, true);
                    }
                    else
                    {
                        result.Add(key, false);
                    }  
                }
                else
                {
                    result.Add(key, false);
                }
            }
            Device.StopCapture();
            Device.Close();
            return result;
        }
    }
}
